package mutipackage;

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class AsResponseDecoder extends CumulativeProtocolDecoder {
	private final Charset charset;
	CharsetDecoder charsetDecoder ;

	public AsResponseDecoder(Charset charset) {
		this.charset = charset;
		charsetDecoder = this.charset.newDecoder();
	}

	@Override
	protected boolean doDecode(IoSession iosession, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {
		int msgLen = ServerConfiguration.MSG_HEADER_LEN;// 4字节判断消息长度
		if (in.remaining() > msgLen) {
			in.mark();
			int length = in.getInt();
			System.out.println("package length="+length);
			if (length - msgLen > in.remaining()) {
				in.reset();
				return false;
			} else {
				int limit = in.limit();
				in.limit(in.position() + length - msgLen);
				System.out.println("po="+in.position()+",limit="+in.limit()  );
				String content = in.getString(charsetDecoder);
				out.write(content);
				in.limit(limit);
				if (in.remaining() > 0) {
					return true;
				}
			}
		}
		return false;
	}

}